<template>
    <div>
        <flexbox justify="flex-end" v-if="detail.processType === '1' && !disabled">
            <a-button :disabled="!checkedProductIds.length" @click="handleOpenRelateFileModal" type="primary">关联更新包</a-button>
        </flexbox>
        <a-table rowKey="id" size="small" :row-selection="detail.processType === '1' && !disabled ? rowSelection : null" :columns="tableColumns" :data-source="proList" :pagination="false">
            <template #title>
                <slot name="title" />
            </template>
            <template #requireType="{ record }">
                <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
            </template>
            <template #level="{ record }">
                <h-level :level="record.level" v-if="record.level" />
            </template>
            <template #requireDescShow="{ record }">
                <a-tooltip :title="setText(record.requireDescShow)">
                    <div class="text-bre2">{{ setText(record.requireDescShow) }}</div>
                </a-tooltip>
            </template>
            <template #jiraUrl="{ record }">
                <a @click="jumpTo(record.jiraUrl)" v-if="record.jiraUrl">{{ $filters.jiraUrlFilter(record.jiraUrl) }}</a>
            </template>
            <template #versionUpdatePacks="{ record, index: recordIndex }">
                <flexbox v-for="(item, index) of record.versionUpdatePacks" :key="item.id">
                    <a-tooltip :title="item.fileName">
                        <div style="flex: 1" v-fitText>{{ item.fileName }}</div>
                    </a-tooltip>
                    <CloseOutlined class="delete-icon" @click.stop="handleRemove(recordIndex, index)" v-if="!disabled" />
                </flexbox>
            </template>
            <template #action="{ record }">
                <a @click="showDetail(record.id)">详情</a>
                <!-- 待开始或者需求基线才可以删除 -->
                <div style="display: inline-block" v-if="!disabled">
                    <a-divider type="vertical" />
                    <a @click="handleDelete(record.id)">移除</a>
                </div>
            </template>
        </a-table>
        <a-modal title="产品需求关联更新包" centered okText="关联" v-model:visible="visible" :width="600" @ok="handleRelateFile" @cancel="handleCancel">
            <a-form layout="inline" :model="form" ref="ruleFormRef" :rules="rules">
                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item label="选择" name="file">
                            <a-select mode="multiple" v-model:value="form.file" style="width: 100%" placeholder="请选择与该需求相关的更新包" @change="handleChange">
                                <a-select-option :value="item.id" :key="item.id" v-for="item of fileOptions">
                                    {{ item.fileName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { HLevel, HProductType } from '@/components';
import { CloseOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import api from '@/api';
import { deepClone } from '@/utils/util';
import { message } from 'ant-design-vue';
import { defineComponent, ref, unref, toRefs, computed, watch, reactive } from 'vue';
export default defineComponent({
    components: {
        HLevel,
        HProductType,
        CloseOutlined
    },
    props: {
        disabled: {
            type: Boolean,
            default: false
        },
        list: {
            type: Array,
            default: () => []
        },
        stepStatus: {
            type: String,
            default: ''
        },
        detail: {
            type: Object,
            default: () => ({})
        },
        hasAuth: { type: Boolean, default: false }
    },
    emits: ['deleteHandle', 'success'],
    setup(props, { emit }) {
        const router = useRouter();
        const ruleFormRef = ref<any>();
        const state = reactive<any>({
            form: {
                file: []
            },
            visible: false,
            fileOptions: [],
            rules: {
                file: [{ required: true, message: '关联更新包不能为空', type: 'array', trigger: 'change' }]
            },
            checkedProductIds: [],
            proList: []
        });
        const tableColumns = computed(() => {
            const tableColumns: Recordable[] = [
                {
                    title: '产品需求编号',
                    dataIndex: 'requireNumber',
                    ellipsis: true
                },
                {
                    title: '产品需求名称',
                    dataIndex: 'requireName',
                    ellipsis: true
                },
                {
                    title: '需求描述',
                    dataIndex: 'requireDescShow',
                    slots: { customRender: 'requireDescShow' }
                }
            ];
            if (props.detail.processType === '1') {
                tableColumns.push({
                    title: '关联更新包',
                    dataIndex: 'versionUpdatePacks',
                    slots: { customRender: 'versionUpdatePacks' }
                });
            }
            return [
                ...tableColumns,
                {
                    title: '操作',
                    key: 'action',
                    width: 100,
                    slots: { customRender: 'action' },
                    align: 'center'
                }
            ];
        });
        const rowSelection = computed(() => {
            return {
                selectedRowKeys: state.checkedProductIds,
                onChange: (selectedRowKeys, selectedRows) => {
                    state.checkedProductIds = selectedRowKeys;
                }
            };
        });
        const showDetail = (id: number) => {
            router.push({
                path: '/productRequire/productDetail',
                query: {
                    id
                }
            });
        };
        const getUpdateFile = async () => {
            const query = {
                versionId: props.detail.id,
                productIds: state.checkedProductIds.join(',')
            };
            const { success, moule } = await api.versionModel.findVersionUpdatePacks(query);
            if (success) {
                state.fileOptions = [...moule];
            }
        };
        const jumpTo = (link) => {
            window.open(link, '_blank');
        };
        const handleOpenRelateFileModal = () => {
            getUpdateFile();
            state.visible = true;
            unref(ruleFormRef)?.clearValidate();
        };
        const handleRelateFile = () => {
            unref(ruleFormRef)
                .validate()
                .then(async () => {
                    const query: any = [];
                    state.checkedProductIds.forEach((item) => {
                        const index = state.proList.findIndex((elem) => elem.id === item);
                        const versionUpdatePacks: any = deepClone(state.proList[index].versionUpdatePacks || []);
                        state.fileOptions.forEach((item) => {
                            if (state.form.file.includes(item.id)) {
                                versionUpdatePacks.push(item);
                            }
                        });
                        query.push({
                            id: item,
                            versionUpdatePacks
                        });
                    });
                    const { success, errorMsg } = await api.productRequireModel.saveVersionUpdatePacks(query);
                    if (success) {
                        state.visible = false;
                        state.checkedProductIds.forEach((item) => {
                            const index = state.proList.findIndex((elem) => elem.id === item);
                            const versionUpdatePacks: any = state.proList[index].versionUpdatePacks || [];
                            state.fileOptions.forEach((item) => {
                                if (state.form.file.includes(item.id)) {
                                    versionUpdatePacks.push(item);
                                }
                            });
                            state.proList[index].versionUpdatePacks = versionUpdatePacks;
                        });
                        state.form.file = [];
                        state.checkedProductIds = [];
                    } else {
                        message.error(errorMsg);
                    }
                });
        };
        const handleRemove = async (recordIndex, index) => {
            const id = state.proList[recordIndex].id;
            const versionUpdatePacks = state.proList[recordIndex].versionUpdatePacks;
            versionUpdatePacks.splice(index, 1);
            const query = [
                {
                    id,
                    versionUpdatePacks
                }
            ];
            const { success, errorMsg } = await api.productRequireModel.saveVersionUpdatePacks(query);
            if (success) {
                message.success('删除成功');
                state.proList[recordIndex].versionUpdatePacks = versionUpdatePacks;
            } else {
                message.error(errorMsg);
            }
        };
        const handleChange = (val) => {
            state.form.file = val;
        };
        const handleDelete = async (productRequireId: number) => {
            emit('deleteHandle', productRequireId);
        };
        const handleSave = async (index: number) => {
            const query = {
                ...state.proList[index],
                businessChange: true
            };
            const { success } = await api.productRequireModel.updateProduct([query]);
            if (success) {
                message.success('操作成功');
            }
        };
        const handleClear = (index: number) => {
            state.proList[index].verOpinion = '';
            handleSave(index);
        };
        const handleCancel = () => {
            state.visible = false;
            state.form.file = [];
        };
        const setText = (html) => {
            let txt: any = document.createElement('div');
            txt.innerHTML = html;
            const content = txt.innerText || txt.textContent;
            txt = null;
            return content;
        };
        watch(
            () => props.list,
            (n) => {
                state.proList = n ? deepClone(n) : [];
            },
            { immediate: true }
        );

        return {
            ruleFormRef,
            ...toRefs(state),
            tableColumns,
            handleOpenRelateFileModal,
            handleRelateFile,
            handleChange,
            handleDelete,
            rowSelection,
            showDetail,
            jumpTo,
            handleSave,
            handleClear,
            handleRemove,
            handleCancel,
            setText
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.ant-table-row) {
    p {
        margin: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
.canEdit {
    cursor: pointer;
    color: @primary-color;
}
.disabledEdit {
    cursor: not-allowed;
    color: @disable-font-color;
}
.opinion-cont {
    white-space: pre-wrap;
    color: @error-color;
}
.delete-icon {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
}
</style>